package boot

import (
	"github.com/gogf/gf/encoding/gyaml"
	"github.com/nacos-group/nacos-sdk-go/clients"
	nacos_constant "github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/gogf/gf/util/gconv"
)

var (
	DataId = "config.yaml"
	Group = "DEFAULT_GROUP"
)

func LoadCanosConfig() {
	sc := []nacos_constant.ServerConfig{{
		IpAddr: "47.99.211.210",
		Port:   8848,
	}}

	cc := nacos_constant.ClientConfig{
		NamespaceId:         "7b761a5c-7085-4308-b58f-955e064aefd6", // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "logs/config",
		CacheDir:            "logs/cache",
		//RotateTime:          "1h",
		//MaxAge:              3,
		//LogLevel:            "debug",
	}

	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": sc,
		"clientConfig":  cc,
	})
	if err != nil {
		panic(err)
	}

	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: DataId,
		Group:  Group,
	})
	if err != nil {
		panic(err)
	}

	SetNacosConfig(content)
	err = configClient.ListenConfig(vo.ConfigParam{
		DataId: DataId,
		Group:  Group,
		OnChange: func(namespace, group, dataId, data string) {
			SetNacosConfig(data)
		},
	})
}

func SetNacosConfig(content string) {
	config, err := gyaml.Decode([]byte(content))
	if err != nil {
		panic(err)
	}
	SetConfig(gconv.Map(config))
}
